package org.gikolet.ch2.android.logic;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.gikolet.ch2.android.io.Ch2ThreadHeaderPAF;
import org.gikolet.ch2.android.io.LocalSubjectReader;
import org.gikolet.ch2.android.io.LocalSubjectWriter;
import org.gikolet.ch2.dao.DaoException;
import org.gikolet.ch2.dao.ThreadHeaderDao;
import org.gikolet.ch2.data.Board;
import org.gikolet.ch2.data.ThreadHeader;
import org.gikolet.ch2.io.Storage;
import org.gikolet.ch2.io.ThreadHeadersReader;
import org.gikolet.ch2.io.ThreadHeadersReaderProvider;
import org.gikolet.ch2.logic.ThreadHeadersLogic;
import org.gikolet.util.ReflectionString;

import roboguice.inject.ContextScoped;

import com.google.inject.Inject;

@ContextScoped
public class AndroidThreadHeadersLogic implements ThreadHeadersLogic {

	private Board boardCache;
	private List<ThreadHeader> threadHeadersCache;

	@Inject
	private ThreadHeaderDao threadHeaderDao;

	@Inject
	private Storage storage;

	@Inject
	private ThreadHeadersReaderProvider threadHeadersReaderProvider;

	public void update(Board board, boolean cache) throws IOException {
		ThreadHeadersReader reader = this.threadHeadersReaderProvider
				.createThreadHeadersReader(board);

		List<ThreadHeader> subjects = new ArrayList<ThreadHeader>();

		LocalSubjectWriter writer = null;
		try {
			writer = new LocalSubjectWriter(board, storage,
					new Ch2ThreadHeaderPAF(), "MS932");

			ThreadHeader s;
			while ((s = reader.read()) != null) {
				subjects.add(s);
				writer.write(s);
			}

			// とりあえずここでDBの値を取得
			for (ThreadHeader th : subjects) {
				try {
					ThreadHeader tmp = threadHeaderDao.find(th.getBoard()
							.getHostName(), th.getBoard().getPath(), th
							.getThreadKey());

					th.setId(tmp.getId());
					th.setDate(tmp.getDate());
					th.setLastModified(tmp.getLastModified());
					th.setByteSize(tmp.getByteSize());

					System.out.println(ReflectionString.toString(th));

				} catch (DaoException e) {
					if (e.getError() != DaoException.Error.NOT_FOUND) {
						throw e;
					}
				}
			}

		} finally {
			try {
				writer.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		this.boardCache = board;
		this.threadHeadersCache = subjects;
	}

	// キャッシュ
	public List<ThreadHeader> getThreadHeaders(Board board) throws IOException {
		if (board.equals(this.boardCache)) {
			return this.threadHeadersCache;
		}
		ThreadHeadersReader reader = new LocalSubjectReader(board, storage,
				new Ch2ThreadHeaderPAF(), "MS932");

		List<ThreadHeader> subjects = new ArrayList<ThreadHeader>();

		ThreadHeader s;
		while ((s = reader.read()) != null) {
			subjects.add(s);
		}

		return subjects;
	}
}
